<?php

namespace App\Http\Controllers;

use App\Models\AdminMenusModel;
use Illuminate\Http\Request;
use App\Models\AdminRolesModel;
use Illuminate\Support\Facades\Validator;


class RoleController extends BaseController
{

    protected $rule = [
        'name' => 'required',
        'desc' => 'required',
    ];

    protected $message = [];

    public function __construct()
    {
        $this->message = [
            'name.required' => trans("role.name_required"),
            'desc.required' => trans("role.desc_required")
        ];
    }

    /**
     * 角色管理列表页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $name = strval($request->input('name', ''));
        $status = strval($request->input('status', ''));
        $desc = strval($request->input('desc'));

        $create_time = strval($request->input('create_time', ''));
        $create_start_time = 0;
        $create_end_time = 0;
        if (!empty($create_time)) {
            $time = explode(" - ", $create_time);
            $create_start_time = strtotime($time[0]);
            $create_end_time = strtotime($time[1]);
        }
        $arr = [
            'name' => $name,
            'status' => $status,
            'desc' => $desc,
            'create_start_time' => $create_start_time,
            'create_end_time' => $create_end_time
        ];
        $roles = AdminRolesModel::getAdminRolesList($arr);
        return view('role.index', [
            'roles' => $roles,
            'name' => $name,
            'desc' => $desc,
            'status_select' => $status,
            'create_time' => $create_time,
            'status' => AdminRolesModel::$status
        ]);
    }

    /**
     * 角色管理展示页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Request $request)
    {
        if ($request->has('id')) {
            $id = intval($request->input('id'));
            $role = AdminRolesModel::getAdminRoleData(['id' => $id]);
            return view('role.show', ['role' => $role]);
        }
        return view('role.show');
    }

    /**
     * 新增角色操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        $data = $request->input();
        $validator = Validator::make($data, $this->rule, $this->message);
        if (!$validator->passes()) {
            return $this->_failed($validator->errors()->first());
        }
        if (AdminRolesModel::getAdminRolesExists(['name' => $data['name']])) {
            return $this->_failed(trans("role.role_repeat"));
        }
        $data['create_at'] = $request->session()->get('userinfo.id');
        if (!AdminRolesModel::insertAdminRoles($data)) {
            return $this->_failed(trans('common.insert_failed'));
        }
        return $this->_success();
    }

    /**
     * 编辑角色操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $data = $request->input();
        $validator = Validator::make($data, $this->rule, $this->message);
        if (!$validator->passes()) {
            return $this->_failed($validator->errors()->first());
        }
        $role = AdminRolesModel::getAdminRoleData(['id' => $data['id']]);
        if ($role->premission == AdminRolesModel::SUPERROLE) { //超级管理员角色不能编辑
            return $this->_failed(trans("role.cannot_modify_super_role"));
        }
        if ($role->name != $data['name']) {
            if (AdminRolesModel::getAdminRolesExists(['name' => $data['name']])) {
                return $this->_failed(trans("role.role_repeat"));
            }
        }
        $update = [
            'name' => $data['name'],
            'desc' => $data['desc'],
            'update_time' => time(),
            'update_at' => $request->session()->get('userinfo.id')
        ];
        if (!AdminRolesModel::updateAdminRole(['id' => $data['id']], $update)) {
            return $this->_failed(trans("common.update_failed"));
        }
        return $this->_success();
    }

    /**
     * 删除和批量删除角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        if (!$request->ajax()) {
            return $this->_failed(trans("common.illegal_request"));
        }
        $id = strval($request->input('id'));
        if (strpos($id, ",") !== false) {
            $id = array_filter(explode(",", $id));
        } else {
            $id = array($id);
        }
        $roles = AdminRolesModel::getAllAdminRoles(['id' => $id]);
        if (empty($roles)) {
            return $this->_failed(trans('role.not_exists_role'));
        }
        $delIds = [];
        foreach ($roles as $key => $role) {
            if ($role->premission == AdminRolesModel::SUPERROLE) {
                unset($roles[$key]);
                continue;
            }
            if ($role->status == AdminRolesModel::ROLEDISABLE) {
                unset($roles[$key]);
                continue;
            }
            $delIds[] = $role->id;
        }
        if (empty($delIds)) {
            return $this->_failed(trans('role.not_exists_can_del'));
        }
        if (!AdminRolesModel::deleteAdminRoles(['id' => $delIds])) {
            return $this->_failed(trans('common.del_failed'));
        }
        return $this->_success();
    }

    /**
     * 禁用和启用角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function disable(Request $request)
    {
        if (!$request->ajax()) {
            return $this->_failed(trans("common.illegal_request"));
        }
        $data = $request->input();
        $role = AdminRolesModel::getAdminRoleData(['id' => $data['id']]);
        if (empty($role)) {
            return $this->_failed(trans("role.not_exists_role"));
        }
        if ($role->premission == AdminRolesModel::SUPERROLE) { //不能禁用超级管理员
            return $this->_failed(trans("role.cannot_disable_super_role"));
        }
        $status = AdminRolesModel::ROLEENABLE;
        if ($role->status == AdminRolesModel::ROLEENABLE) {
            $status = AdminRolesModel::ROLEDISABLE;
        }
        $update['status'] = $status;
        if (!AdminRolesModel::updateAdminRole(['id' => $data['id']], $update)) {
            return $this->_failed(trans("common.update_failed"));
        }
        return $this->_success();
    }

    /**
     * 角色授权操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function dogrant(Request $request)
    {
        if (!$request->ajax()) {
            return $this->_failed(trans("common.illegal_request"));
        }
        $data = $request->input();
        $role = AdminRolesModel::getAdminRoleData(['id' => $data['id']]);
        if (empty($role)) {
            return $this->_failed(trans("role.not_exists_role"));
        }
        if ($role->premission == AdminRolesModel::SUPERROLE) {
            return $this->_failed(trans("role.cannot_grant_super_role"));
        }
        $update = [
            'premission' => $data['premission'],
            'update_time' => time(),
            'update_at' => $request->session()->get('userinfo.id')
        ];
        if (!AdminRolesModel::updateAdminRole(['id' => $data['id']], $update)) {
            return $this->_failed(trans("common.update_failed"));
        }
        return $this->_success();
    }

    /**
     * 授权页面 需要写入缓存
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function grant(Request $request)
    {
        $id = $request->input('id');
        $role = AdminRolesModel::getAdminRoleData(['id' => $id]);
        $default_premission = !empty($role->premission) ? $role->premission : "";
        $default_premission_arr = !empty($default_premission) ? explode(",", $default_premission) : array();

        //为了处理tree的选中情况
        $child_default_premission = [];
        $unselect_default_premission = [];

        $menus = AdminMenusModel::getAllAdminMenusForLeftMenu(['status' => AdminMenusModel::MENUSHOW]);
        $treemenus = array();
        if (!empty($menus)) {
            foreach ($menus as $module) {  //模块遍历
                $treechildmodule = array();
                if (!empty($module['child'])) {
                    foreach ($module['child'] as $childmodule) { //遍历子模块
                        $treechildmodulemenu = array();
                        if (!empty($childmodule['child'])) {
                            foreach ($childmodule['child'] as $childmodulemenu) {
                                $treechildmodulemenubtn = array();
                                if (!empty($childmodulemenu['child'])) {
                                    foreach ($childmodulemenu['child'] as $childmodulemenbtn) {
                                        $treechildmodulemenubtn [] = [
                                            'title' => $childmodulemenbtn['name'],
                                            'id' => $childmodulemenbtn['id'],
                                            'field' => $childmodulemenbtn['rule'],
                                        ];
                                        if (in_array($childmodulemenbtn['id'], $default_premission_arr) && in_array($childmodulemenu['id'], $default_premission_arr)) {
                                            $child_default_premission[] = $childmodulemenbtn['id'];
                                            $unselect_default_premission[] = $childmodulemenu['id'];
                                        }
                                    }
                                }

                                $treechildmodulemenu[] = [
                                    'title' => $childmodulemenu['name'],
                                    'id' => $childmodulemenu['id'],
                                    'field' => $childmodulemenu['rule'],
                                    'children' => $treechildmodulemenubtn
                                ];

                                if (in_array($childmodulemenu['id'], $default_premission_arr) && in_array($childmodule['id'], $default_premission_arr)) {
                                    if (!in_array($childmodulemenu['id'], $unselect_default_premission)) {
                                        $child_default_premission[] = $childmodulemenu['id'];
                                    }
                                    $unselect_default_premission[] = $childmodule['id'];
                                }
                            }
                        }
                        $treechildmodule[] = [
                            'title' => $childmodule['name'],
                            'id' => $childmodule['id'],
                            'field' => $childmodule['rule'],
                            'children' => $treechildmodulemenu
                        ];

                        if (in_array($childmodule['id'], $default_premission_arr) && in_array($module['id'], $default_premission_arr)) {
                            if (!in_array($childmodule['id'], $unselect_default_premission)) {
                                $child_default_premission[] = $childmodule['id'];
                            }
                        }
                    }
                }
                $treemenus[] = [
                    'title' => $module['name'],
                    'id' => $module['id'],
                    'field' => $module['rule'],
                    'children' => $treechildmodule
                ];
            }
        }
        $data = json_encode($treemenus, JSON_UNESCAPED_UNICODE);
        return view('role.grant', [
            'data' => $data,
            'default_premission' => !empty($child_default_premission) ? implode(",", $child_default_premission) : ""
        ]);
    }
}
